<template>
  <div class="cart-container">
    <div class="cart-header animate__animated animate__fadeInDown">
      <h2><i class="el-icon-shopping-cart-2"></i> 我的购物车</h2>
      <el-button type="primary" icon="el-icon-arrow-left" @click="goBack">返回商城</el-button>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="cartItems.length === 0" class="empty-cart animate__animated animate__fadeIn">
      <i class="el-icon-shopping-cart-full empty-icon"></i>
      <h3>购物车是空的</h3>
      <p>快去挑选一些新鲜的农产品吧</p>
      <el-button type="primary" @click="goToShop">前往商城</el-button>
    </div>
    
    <div v-else class="cart-content animate__animated animate__fadeIn">
      <div class="cart-header-row">
        <el-checkbox v-model="allSelected" @change="toggleSelectAll">全选</el-checkbox>
        <span class="cart-header-item">商品信息</span>
        <span class="cart-header-item">单价</span>
        <span class="cart-header-item">数量</span>
        <span class="cart-header-item">小计</span>
        <span class="cart-header-item">操作</span>
      </div>
      
      <el-card v-for="item in cartItems" :key="item.cartId" class="cart-item-card">
        <div class="cart-item">
          <div class="cart-item-select">
            <el-checkbox v-model="item.selected" @change="updateCartItem(item)"></el-checkbox>
          </div>
          <div class="cart-item-info">
            <div class="cart-item-image">
              <img src="https://via.placeholder.com/80" alt="商品图片" />
            </div>
            <div class="cart-item-name">{{ item.productName }}</div>
          </div>
          <div class="cart-item-price">¥{{ item.price }}</div>
          <div class="cart-item-quantity">
            <el-input-number 
              v-model="item.quantity" 
              :min="1" 
              :max="99" 
              size="small"
              @change="(val) => updateCartItemQuantity(item, val)">
            </el-input-number>
          </div>
          <div class="cart-item-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
          <div class="cart-item-actions">
            <el-button type="danger" size="small" icon="el-icon-delete" @click="removeFromCart(item)">删除</el-button>
          </div>
        </div>
      </el-card>
      
      <div class="cart-footer">
        <div class="cart-ops">
          <el-button type="danger" size="small" @click="clearCart" :disabled="selectedItems.length === 0">
            清空选中商品
          </el-button>
        </div>
        <div class="cart-total">
          <div class="cart-total-info">
            <span>已选择 <strong>{{ selectedItems.length }}</strong> 件商品</span>
            <span>合计: <strong class="total-price">¥{{ totalPrice.toFixed(2) }}</strong></span>
          </div>
          <el-button type="primary" size="medium" @click="checkout" :disabled="selectedItems.length === 0">
            结算 <i class="el-icon-right"></i>
          </el-button>
        </div>
      </div>
    </div>
    
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <span>确定要从购物车中删除这个商品吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </span>
    </el-dialog>
    
    <el-dialog
      title="确认清空"
      :visible.sync="clearDialogVisible"
      width="30%">
      <span>确定要清空已选中的商品吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="clearDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmClear">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import 'animate.css/animate.min.css';

export default {
  name: 'Cart',
  data() {
    return {
      cartItems: [],
      loading: true,
      allSelected: false,
      deleteDialogVisible: false,
      clearDialogVisible: false,
      itemToDelete: null,
      currentUser: null
    };
  },
  computed: {
    // 已选择的商品列表
    selectedItems() {
      return this.cartItems.filter(item => item.selected);
    },
    // 总价
    totalPrice() {
      return this.selectedItems.reduce((total, item) => {
        return total + (item.price * item.quantity);
      }, 0);
    }
  },
  created() {
    this.getCurrentUser();
    this.loadCartItems();
  },
  methods: {
    // 获取当前登录用户
    getCurrentUser() {
      try {
        const userStr = localStorage.getItem('user');
        if (userStr) {
          this.currentUser = JSON.parse(userStr);
        }
        
        if (!this.currentUser || !this.currentUser.id) {
          this.$message.warning('您尚未登录，请先登录系统');
          this.$router.push('/login');
        }
      } catch (error) {
        console.error('获取用户信息失败', error);
        this.$message.error('获取用户信息失败');
      }
    },
    
    // 加载购物车商品
    loadCartItems() {
      if (!this.currentUser || !this.currentUser.id) {
        this.loading = false;
        return;
      }
      
      this.loading = true;
      this.request.get(`/cart/findByUserId/${this.currentUser.id}`).then(res => {
        this.loading = false;
        if (res.code === '200') {
          // 打印API返回数据，用于调试
          console.log('购物车数据:', res.data);
          
          // 处理后端返回的数据
          if (res.data && Array.isArray(res.data)) {
            this.cartItems = res.data.map(item => {
              // 确保selected字段是布尔值
              item.selected = item.selected === true || item.selected === 1;
              return item;
            });
            
            // 更新全选状态
            this.updateSelectAllStatus();
          } else {
            this.cartItems = [];
          }
        } else {
          this.$message.error('获取购物车失败: ' + (res.msg || '未知错误'));
        }
      }).catch(err => {
        this.loading = false;
        console.error('加载购物车失败:', err);
        this.$message.error('网络错误，无法加载购物车');
      });
    },
    
    // 更新全选状态
    updateSelectAllStatus() {
      if (this.cartItems.length === 0) {
        this.allSelected = false;
      } else {
        this.allSelected = this.cartItems.every(item => item.selected);
      }
    },
    
    // 全选/取消全选
    toggleSelectAll(val) {
      // 更新所有商品的选中状态
      this.cartItems.forEach(item => {
        item.selected = val;
        this.updateCartItem(item);
      });
    },
    
    // 更新购物车商品
    updateCartItem(item) {
      if (!this.currentUser || !this.currentUser.id) {
        this.$message.warning('请先登录');
        return;
      }
      
      // 现在使用后端API更新选中状态
      const params = {
        selected: item.selected ? 1 : 0
      };
      
      this.request.put(`/cart/update/${item.cartId}`, params).then(res => {
        if (res.code !== '200') {
          this.$message.error('更新失败: ' + (res.msg || '未知错误'));
          // 更新失败，恢复原状态
          this.loadCartItems();
        } else {
          console.log(`商品[${item.productName}]选中状态已更新: ${item.selected}`);
        }
        // 更新全选状态
        this.updateSelectAllStatus();
      }).catch(err => {
        console.error('更新购物车失败:', err);
        this.$message.error('网络错误，更新失败');
        // 更新失败，恢复原状态
        this.loadCartItems();
      });
    },
    
    // 更新商品数量
    updateCartItemQuantity(item, quantity) {
      if (!this.currentUser || !this.currentUser.id) {
        this.$message.warning('请先登录');
        return;
      }
      
      const params = {
        quantity: quantity
      };
      
      this.request.put(`/cart/update/${item.cartId}`, params).then(res => {
        if (res.code === '200') {
          this.$message.success('数量已更新');
        } else {
          this.$message.error('更新失败: ' + (res.msg || '未知错误'));
          // 更新失败，恢复原状态
          this.loadCartItems();
        }
      }).catch(err => {
        console.error('更新购物车失败:', err);
        this.$message.error('网络错误，更新失败');
        // 更新失败，恢复原状态
        this.loadCartItems();
      });
    },
    
    // 删除购物车商品
    removeFromCart(item) {
      this.itemToDelete = item;
      this.deleteDialogVisible = true;
    },
    
    // 确认删除
    confirmDelete() {
      if (!this.currentUser || !this.currentUser.id || !this.itemToDelete) {
        this.deleteDialogVisible = false;
        return;
      }
      
      this.request.delete(`/cart/deleteById/${this.itemToDelete.cartId}`).then(res => {
        this.deleteDialogVisible = false;
        if (res.code === '200') {
          this.$message.success('商品已从购物车中删除');
          // 重新加载购物车
          this.loadCartItems();
        } else {
          this.$message.error('删除失败: ' + (res.msg || '未知错误'));
        }
      }).catch(err => {
        this.deleteDialogVisible = false;
        console.error('删除购物车商品失败:', err);
        this.$message.error('网络错误，删除失败');
      });
    },
    
    // 清空购物车
    clearCart() {
      if (this.selectedItems.length === 0) {
        this.$message.warning('请先选择要删除的商品');
        return;
      }
      
      this.clearDialogVisible = true;
    },
    
    // 确认清空
    confirmClear() {
      if (!this.currentUser || !this.currentUser.id) {
        this.clearDialogVisible = false;
        return;
      }
      
      if (this.selectedItems.length === 0) {
        this.clearDialogVisible = false;
        this.$message.warning('没有选中商品');
        return;
      }
      
      // 由于没有批量删除接口，我们循环删除选中的商品
      const total = this.selectedItems.length;
      let completed = 0;
      let success = 0;
      
      const deleteNextItem = (index) => {
        if (index >= this.selectedItems.length) {
          // 所有删除操作完成
          this.clearDialogVisible = false;
          if (success === total) {
            this.$message.success('已清空选中商品');
          } else {
            this.$message.warning(`成功删除 ${success}/${total} 个商品`);
          }
          // 重新加载购物车
          this.loadCartItems();
          return;
        }
        
        const item = this.selectedItems[index];
        this.request.delete(`/cart/deleteById/${item.cartId}`).then(res => {
          completed++;
          if (res.code === '200') {
            success++;
          }
          // 继续删除下一个
          deleteNextItem(index + 1);
        }).catch(err => {
          console.error('删除购物车商品失败:', err);
          completed++;
          // 继续删除下一个
          deleteNextItem(index + 1);
        });
      };
      
      // 开始删除第一个
      deleteNextItem(0);
    },
    
    // 结算
    checkout() {
      if (this.selectedItems.length === 0) {
        this.$message.warning('请先选择要结算的商品');
        return;
      }
      
      // 跳转到结算页面，并传递选中的商品信息
      this.$router.push({
        path: '/checkout',
        query: { from: 'cart' }
      });
    },
    
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    
    // 前往商城
    goToShop() {
      this.$router.push('/shop');
    }
  }
}
</script>

<style scoped>
.cart-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.cart-header h2 {
  margin: 0;
  color: #303133;
}

.loading-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin-top: 20px;
}

.empty-cart {
  text-align: center;
  padding: 50px 0;
  background: #fff;
  border-radius: 4px;
  margin-top: 20px;
}

.empty-icon {
  font-size: 80px;
  color: #c0c4cc;
  margin-bottom: 20px;
}

.empty-cart h3 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.empty-cart p {
  font-size: 16px;
  color: #909399;
  margin-bottom: 20px;
}

.cart-content {
  background: #fff;
  border-radius: 4px;
  margin-top: 20px;
}

.cart-header-row {
  display: grid;
  grid-template-columns: 80px 3fr 1fr 1fr 1fr 1fr;
  padding: 15px 10px;
  background: #f5f7fa;
  border-radius: 4px 4px 0 0;
  font-weight: bold;
  color: #606266;
}

.cart-header-item {
  text-align: center;
}

.cart-item-card {
  margin-bottom: 10px;
}

.cart-item {
  display: grid;
  grid-template-columns: 80px 3fr 1fr 1fr 1fr 1fr;
  align-items: center;
}

.cart-item-select {
  display: flex;
  justify-content: center;
  align-items: center;
}

.cart-item-info {
  display: flex;
  align-items: center;
  padding: 10px;
}

.cart-item-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.cart-item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.cart-item-name {
  font-size: 16px;
  color: #303133;
}

.cart-item-price,
.cart-item-quantity,
.cart-item-subtotal,
.cart-item-actions {
  display: flex;
  justify-content: center;
  align-items: center;
}

.cart-item-price,
.cart-item-subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 0 0 4px 4px;
}

.cart-total {
  display: flex;
  align-items: center;
}

.cart-total-info {
  margin-right: 20px;
}

.cart-total-info span {
  margin-right: 20px;
  color: #606266;
}

.total-price {
  color: #f56c6c;
  font-size: 20px;
}
</style> 